// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command
const $ = db.command.aggregate

// 分页查询诉求评论
const pageAppealComment = async function (params) {
  const wxContext = cloud.getWXContext()

  let appealId = params.appealId
  let pageNO = params.pageNO || 1
  let pageSize = params.pageSize || 10


  let commentList = await db.collection('appealComment')
    .aggregate()
    // 匹配项
    .match({
      appealId: appealId
    })

    // 连表查询 用户信息
    .lookup({
      from: 'user',
      localField: '_openid',
      foreignField: '_openid',
      as: 'userInfo'
    })
    .addFields({
      userInfo: $.arrayElemAt(['$userInfo', 0])
    })

    .sort({
      'createTime': -1
    })
    .skip((pageNO - 1) * pageSize).limit(pageSize)
    .end()


  return commentList.list || []

}

module.exports = pageAppealComment